package com.xucia.jsponic.security;

import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import org.mozilla.javascript.NativeArray;

import com.xucia.jsponic.data.Persistable;
import com.xucia.jsponic.data.PersistableImpl;

public class Group extends NativeArray implements java.security.acl.Group{
	public Group() {
		super(0);
	}

	public boolean addMember(Principal user) {
		return add(user);
	}

	public boolean isMember(final Principal member) {
		return (Boolean) User.doPriviledgedAction(new PrivilegedAction<Boolean>() {
			public Boolean run() {
				for (Object aMember: Group.this) {
					if (aMember == member)
						return true;
					if ((aMember instanceof java.security.acl.Group) && ((java.security.acl.Group)aMember).isMember(member))
						return true;
				}
				return false;
			}
		});
	}

	public Enumeration members() {
		return Collections.enumeration(this);
	}

	public boolean removeMember(Principal user) {
		return remove(user);
	}

	public String getName() {
		return (String) get("name");
	}

	@Override
	public void add(int index, Object element) {
		super.add(index, element);
		PersistableImpl.resetComputedPermissions();

//		User.recalculateGroupMembership(this); // TODO: This goes through every member, it could be optimized to just do the new users
	}

	@Override
	public boolean add(Object o) {
		System.err.println("add to group");
		boolean retValue = super.add(o);
		PersistableImpl.resetComputedPermissions();
		//User.recalculateGroupMembership(this); // TODO: This goes through every member, it could be optimized to just do the new users
		return retValue;
	}

	@Override
	public Object remove(int index) {
		Object retValue = super.remove(index);
		PersistableImpl.resetComputedPermissions();
		return retValue;
	}

	@Override
	public boolean remove(Object oldMember) {
		boolean retValue = super.remove(oldMember);
		PersistableImpl.resetComputedPermissions();
		return retValue;
	}

	@Override
	public void clear() {
		super.clear();
		PersistableImpl.resetComputedPermissions();

	}
	

}
